// 二分搜索

#include <stdio.h>

int search(int key, int a[], int len);

int main(int argc, char const *argv[])
{
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    r = search(7, a, sizeof(a) / sizeof(a[0]));
    printf("%d\n", r);
    
    return 0;
}

// 二分搜索，数据必须是已排好序的
int search(int key, int a[], int len)
{
    int ret = -1;
    int left = 0;
    int right = len - 1;
    while (left < right)
    {
        int mid = (left + right) / 2;
        if (a[mid] == k)
        {
            ret = mid;
            break;
        }
        else if (a[mid] > k)
        {
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }
}